from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import pandas as pd
import numpy as np
import joblib
from django.views.decorators.http import require_http_methods
import json
class Options:
    bar = {
        "title": {
            "text": "区域房价对比"
        },
        "xAxis": {
            "data": [],
            "axisLabel": {
                "rotate": 45
            }
        },
        "yAxis": {},
        "series": [
            {
                "name": "价格",
                "type": "bar",
                "data": []
            }
        ]
    }
    
    pie= {
            "title": {
                
                "left": 'center'
            },
            'tooltip': {
                "trigger": 'item'
            },
            'legend': {
                "orient": 'vertical',
                "left": 'left'
            },
            'toolbox' :{
            'show' : 'true',
            'feature' :{
                'mark': { 'show' : 'true'},
                'dataView' :{ 'show': 'true',
                              'readOnly' : 'false'},
                'restore' : {'show': 'true'},
                'saveAsImage': {'show' :'true'}
             }
        },
            'series': [
                {
                    'name': '房型',
                    'type': 'pie',
                    'radius': '50%',
                    "data": [],
                    'emphasis': {
                        'itemStyle': {
                            'shadowBlur': 10,
                            'shadowOffsetX': 0,
                            'shadowColor': 'rgba(0,0,0,0.5)'
                        }
                    }

                }
            ]
        }
    scatter = {
        'title':{
          'text':'建筑面积与房价散点图',
          'left':'center'
        },
        'xAxis' : {
            'name':'/㎡'
        },
        'yAxis' : {
            'name':'万元'
        },
        'series' : [
            {
                'symbolSize' : 20,
                'data' : [],
                'type' : 'scatter'
            }
        ]
    }
    smooth ={
        'title' :{
            'text' :'历年房价走势',
            'left' :'center'
        },
        'tooltip': {
            'trigger': 'item',
            'axisPointer': {
                'type': 'shadow'
            }
        },
        'xAxis' : {
            'type' : 'category',
            'data' : []
        },
        'yAxis' :{
            'type' : 'value'
        },
        'toolbox' :{
            'show' : 'true',
            'feature' :{
                'mark': { 'show' : 'true'},
                'dataView' :{ 'show': 'true',
                              'readOnly' : 'false'},
                'restore' : {'show': 'true'},
                'saveAsImage': {'show' :'true'}
             }
        },
        'series':[
            {
                'data' :[],
                'type' : 'line',
                'smooth' : True
            }
        ]
    }
    pie1 ={
        'title' :{
            'text' :'城市户型统计',
            'left' :'center'
        },
        'tooltip':{
            'trigger': 'item',
            'formatter' : '{a} <br/>{b}  : {c} ({d}%)'
        },
        'legend': {
            'left': 'center',
            'top': 'bottom',

        },
        'toolbox' :{
            'show' : 'true',
            'feature' :{
                'mark': { 'show' : 'true'},
                'dataView' :{ 'show': 'true',
                              'readOnly' : 'false'},
                'restore' : {'show': 'true'},
                'saveAsImage': {'show' :'true'}
             }
        },
        'series':{
            "data": [],
            'name' : '户型',
            'type' : 'pie',
            'radius' : [20,120],

            'center' : ['50%','50%'],
            'roseType' : 'radius',
            'itemStyle':{
                'borderRadius' :5 }

        }
    }
    geo ={
       'title':{
           'text': '地区房价图'
       },
        'tooltip':{
            'trigger':'item',
            'formatter':'{b}<br/>{c} '
        },
        'visualMap' :{
            'min':1000,
            'max':150000,
            'text': ['High','Low'],
            'realtime':'false',
            'inRange':{
                'color' :['lightskyblue','yellow','red']
            }
        },
        'series':{
            'type':'map',
            'map':'china',
            'label' :{
              'show': 'true'
              },
             'data':[],

        }
    }
    bar1 = {
        "title": {
            "text": "不同交易权属对房价影响"
        },
        "xAxis": {
            "data": [],
            "axisLabel": {
                "rotate": 45
            }
        },
        "yAxis": {},
        "series": [
            {
                "name": "价格",
                "type": "bar",
                "data": []
            }
        ]
    }

    box ={
     'title': [
            {   'text': 'Michelson-Morley Experiment',
                'left': 'center'},
            {
                'text': 'upper: Q3 + 1.5 * IQR \nlower: Q1 - 1.5 * IQR',
                'borderColor': '#999',
                'borderWidth': 1,
                'textStyle': {
                    'fontWeight': 'normal',
                    'fontSize': 14,
                    'lineHeight': 20  },
                'left': '10%',
                'top': '90%'} ],
     'dataset': [
         { 'source': []},
         {
            'transform': {
            'type': 'boxplot',
            'config': {'itemNameFormatter': 'expr {value}'} }},
        {
            'fromDatasetIndex': 1,
            'fromTransformResult': 1}],
     'tooltip': {
        'trigger': 'item',
        'axisPointer': {
            'type': 'shadow'
        }},
     'grid': {
        'left': '10%',
        'right': '10%',
        'bottom': '15%'
    },
     'xAxis': {
        'type': 'category',
        'boundaryGap': 'true',
        'nameGap': 30,
        'splitArea': {
            'show': 'false'},
        'splitLine': {
            'show': 'false'},
        'data':[]},
     'yAxis': {
        'type': 'value',
        'name': '元/平米',
        'splitArea': {
            'show': 'true'}},
     'series': [
        {
            'name': 'boxplot',
            'type': 'boxplot',
            'datasetIndex': 1},
        {   'name': 'outlier',
            'type': 'scatter',
            'datasetIndex': 2}]}

    bar2 ={
        'tooltip': {
            'trigger': 'item',
            'axisPointer': {
                'type': 'shadow'
            }
        },
        'toolbox': {
            'feature': {
                'dataView': {'show': 'true', 'readOnly': 'false'},
                'magicType': {'show': 'true', 'type': ['line', 'bar']},
                'restore': {'show': 'true'},
                'saveAsImage': {'show': 'true'}
            }
        },
        'title':{
            'text' :"",
            'left' :'center'
        },
        'xAxis': {
            'type': 'category',
            'data': [],
             "axisLabel": {
                "rotate": 45
            }
            
        },
        'yAxis': {
            'type': 'value'
        },
        'series': [
            {
                "name": "平均价格柱状",
                'data': [],

                'type': 'bar'
            },
            {
                "name":"平均价格折线",
                'type':"line",
                'data':[]
            }
        ]
    }

    ditu={
      'visualMap':{
            'min' :'4000',
            'max' :'150000',
            'realtime' :'false',
            'calculable' :'true',
            'inRange' :{
                'color' :['lightskyblue','yellow','orangered']
                        }
            },
        'title':{
            'text':'',
            'left':'center'
        },
        'tooltip':{},
        'series':[
            {
                'name':'',
                'type':'map',
                'map':'',
                'label':{
                    'show' :'true'
                },
                'data':[]
            }
        ]
        }
def hello(request):

    options = Options.bar

    citys = ["上海","北京","哈尔滨","广州","武汉","郑州","重庆","长沙"]
    city = request.GET.get("city")
    if  city not in citys:
        return render(request, "invalid.html")

    df = pd.read_csv(f"{settings.BASE_DIR}/templates/data/{city}.csv")

    df = df.loc[:, ["价格", "地区"]].groupby("地区")["价格"].mean().astype(int)
    df = df.sort_values()

    options['title']['text']=city+"市区域房价对比"
    options['xAxis']['data']=df.index.tolist()
    options['series'][0]['data'] = df.tolist()

    return JsonResponse(Options().bar)


def region(request):
    #画城市房价对比
    options = Options.pie
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "invalid.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/data/{city}.csv")

    type = df['交易权属']
    type_counts = type.value_counts()
    data_points = [{'name': name, 'value': round(count / type_counts.sum() * 100, 2)} for name, count in type_counts.items()]

    options['title']['text'] = city +'城市房屋产权性质分类'
    options['series'][0]['data'] = data_points
    return JsonResponse(options)
    #return render(request, "first.html")
def area(request):
    options2 = Options.scatter
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/data/{city}.csv")
    area1 = df['建筑面积'].replace('㎡','',regex=True)
    price = df['价格']
    
    data_points = [(area, price) for area, price in zip(area1, price)]
    options2['series'][0]['data'] = data_points
    return JsonResponse(options2)
    # return render(request, "first.html")
def history(request):
    options3 = Options.smooth
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/result_output/{city}.csv")
    year1 = df['年份'].tolist()
    price1 = df['房价'].astype(int).tolist()
    options3['title']['text'] = city +"历年房价走势"
    options3['xAxis']['data'] = year1
    options3['series'][0]['data'] = price1

    return JsonResponse(options3)
def huxing(request):
    options4 = Options.pie1
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/change/{city}.csv")

    hux = df['房屋户型']
    h = hux.value_counts()
    threshold = 0.5 / len(h) * 100
    data_points = [{'name': name,'value':  round(count / h.sum() * 100, 2)} for name, count in h.items() if count / h.sum() * 100 > threshold ]

    #options4['legend']['data'] = h.index
    options4['series']['data'] = data_points

    return JsonResponse(Options.pie1)
    
def Ditu(request):
    options5 = Options.geo
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/result5/{city}.csv")
    price = df['价格']
    area = df['地区']

    data_points = [{'name': name,'value':val  } for name,val in zip(area,price) ]

    #options5['series']['map'] = city
    options5['series']['data'] = data_points

    return JsonResponse(options5)
    
    
@require_http_methods(["POST"])
def compare(request):
    compare = {
        "title": {
            "text": '历年房价对比'
        },
        
        'tooltip': {
            'trigger': 'item',
            'axisPointer': {
                'type': 'shadow'
            }
        },
        "legend": {
            "data": []
        },
        "grid": {
            "left": '3%',
            "right": '4%',
            "bottom": '3%',
            "containLabel": True
        },
        "toolbox": {
            "feature": {
                "saveAsImage": {}
            }
        },
        "xAxis": {
            "type": 'category',
            "boundaryGap": False,
            "data": [i for i in range(2011, 2025)]
        },
        "yAxis": {
            "type": 'value'
        },
        "series": []
    }
    option = compare
    data = json.loads(request.body)
    citys = data.get("citys")
    for city in citys:
        df = pd.read_csv(f"{settings.BASE_DIR}/templates/price/{city}.csv")
        df = df[df['价格']!="价格"].reset_index().drop("index",axis=1)
        df['时间'] = df['时间'].apply(lambda x:int(x.split('-')[0]))
        df["价格"] = df["价格"].apply(lambda price: price.split("元")[0]).astype(int)
        df = df.groupby('时间')['价格'].mean().astype(int)
        item = {
            "name": city,
            "type": "line",
            "smooth":"true",
            "data": df.tolist()
        }
        option['legend']['data']=citys
        option['series'].append(item)
    return JsonResponse(option)
    
    
def yx(request):
    options8 = Options.bar2
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    influence = request.GET.get("influence")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/data/{city}.csv")
    if influence == '电梯':
     df = df.loc[:, ["价格", "配备电梯"]].groupby("配备电梯")["价格"].mean().astype(int)
     df = df.sort_values()
     df = df[df.index.isin(["有", "无"])]
     options8['title']['text'] = city + "是否有电梯对房价影响"
     options8['xAxis']['data'] = df.index.tolist()
     options8['series'][0]['data'] = df.tolist()
     options8['series'][1]['data'] = df.tolist()
     return JsonResponse(options8)
    
    
    elif influence == '装修程度':

        df = df.loc[:, ["价格", "装修情况"]].groupby("装修情况")["价格"].mean().astype(int)
        df = df.sort_values()
        df = df[df.index.isin(["精装", "简装","毛坯"])]

        options8['title']['text'] = city + "装修情况对房价影响"
        options8['xAxis']['data'] = df.index.tolist()
        options8['series'][0]['data'] = df.tolist()
        options8['series'][1]['data'] = df.tolist()
        return JsonResponse(options8)

    elif influence == '楼层':
        df['所在楼层'] = df['所在楼层'].apply(lambda x:x[0:3])
        df = df.loc[:, ["价格", "所在楼层"]].groupby("所在楼层")["价格"].mean().astype(int)
        df = df.sort_values()
        #df = df[df.index.isin(["精装", "简装","毛坯"])]

        options8['title']['text'] = city + "楼层对房价影响"
        options8['xAxis']['data'] = df.index.tolist()
        options8['series'][0]['data'] = df.tolist()
        options8['series'][1]['data'] = df.tolist()
        return JsonResponse(options8)

    elif influence == '产权性质':
        options6 = Options.bar2
        df = df.loc[:, ["价格", "交易权属"]].groupby("交易权属")["价格"].mean().astype(int)
        df = df.sort_values()

        options6['title']['text'] = city + "不同产权性质对房价影响"
        options6['xAxis']['data'] = df.index.tolist()
        options6['series'][0]['data'] = df.tolist()
        options6['series'][1]['data'] = df.tolist()
        return JsonResponse(options6)

    elif influence == '地区':
        options = Options.bar2

        df = df.loc[:, ["价格", "地区"]].groupby("地区")["价格"].mean().astype(int)
        df = df.sort_values()

        options['title']['text'] = city + "区域房价对比"
        options['xAxis']['data'] = df.index.tolist()
        options['series'][0]['data'] = df.tolist()
        options['series'][1]['data'] = df.tolist()

        return JsonResponse(options)
    elif influence == '房屋面积':
        options2 = Options.scatter

        area1 = df['建筑面积'].replace('㎡', '', regex=True)
        price = df['价格']

        data_points = [(area, price) for area, price in zip(area1, price)]
        options2['series'][0]['data'] = data_points
        
        return JsonResponse(options2)
        
def pred(request):
    city = request.GET.get("city")
    #数据处理
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/price/{city}.csv")
    try:
        df['时间'] = pd.to_datetime(df['时间'], errors='coerce')
        df['价格'] = df['价格'].apply(lambda x: x.split("元")[0])
    except Exception as e:
        print(f"An error occurred: {e}")
    df = df.dropna(subset=['时间'])  # 删除'date'列中包含NaT的行
    df['年'] = df['时间'].dt.year
    df['月'] = df['时间'].dt.month
    df['年月'] = df['年'] + df['月'] / 10
    X = df['年月'].astype(float).tolist()
    Y = df['价格'].astype(int).tolist()
    #拟合
    fit = np.polyfit(X, Y, deg=4)
    X += [2024+i/10 for i in range(2,25)]
    y_pred = np.polyval(fit, np.array(X))
    option = {
        "xAxis": {
            "name":'年',
            "type": 'value',
            "interval":1,
            "min":2011,
            "max":2027
        },
        "yAxis": {
            "name":"平均房价"
        },
        "series": [
            {
                "symbolSize": 5,
                "data": [item for item in zip(X,y_pred)],
                "type": 'scatter'
            }
        ]
    }
    return JsonResponse(option)
def getDistrict(request):
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/data/{city}.csv")

    district = df['地区'].unique().tolist()

    return JsonResponse({'district':district})
def predict(request):
    model = joblib.load(f"{settings.BASE_DIR}/templates/multiple_regression.pkl")
    new_data = pd.DataFrame({
        '城市': [request.GET.get("city")],
        '地区': [request.GET.get("district")],
        '建筑面积': [request.GET.get("area")],
        '装修情况': [request.GET.get("decoration")],
        '配备电梯': [request.GET.get("elevator")]
    })
    a = request.GET.get("area")
    price_per_sqm = model.predict(new_data)
    total_price = price_per_sqm[0] * int(a)
    result={
        "price":round(price_per_sqm[0],2),
        "total_price":round(total_price,0)
    }
    return JsonResponse(result)
def map(request):
    options9 = Options.ditu
    citys = ["上海", "北京", "哈尔滨", "广州", "武汉", "郑州", "重庆", "长沙"]
    Maps: ['BeiJing', "ShangHai", "ZhengZhou", "ChangSha", "GuangZhou", "ChongQing", "HaErBin", "WuHan"]
    city = request.GET.get("city")
    if city not in citys:
        return render(request, "first.html")
    df = pd.read_csv(f"{settings.BASE_DIR}/templates/ditu/{city}.csv")
   
    dis =df['地区']
    d = dis.value_counts()
    p  = df.loc[:, ["价格", "地区"]].groupby("地区")["价格"].mean().astype(int)
    p_min = p.min()
    p_max = p.max()
    data_point = [{'name':name+'区','value':val} for name ,val in p.items()]
    options9['series'][0]['data'] = data_point
    options9['title']['text']  = city+'地图'
    options9['series'][0]['map'] = city
    options9['visualMap']['min'] = p_min.astype(str)
    options9['visualMap']['max'] = p_max.astype(str)
    return JsonResponse(options9)

